<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :sm="24" :lg="24">
        <div class="bottom-table">
          <div class="table-header">
            <div class="table-title" v-if="weekTitle && weekTitle.length > 0">{{ weekTitle }}</div>
            <div class="table-title" v-else>xxxx-xx-xx至xxxx-xx-xx招标安排</div>
            <div class="btn-groups">
              <el-button type="primary" size="mini" plain @click="handleSwitch(-1)">上一周</el-button>
              <el-button type="primary" size="mini" plain @click="handleSwitch(1)">下一周</el-button>
              <el-button type="primary" size="mini" plain @click="handleSwitch(0)">本 周</el-button>
              <el-button type="warning" size="mini" plain @click="handlePrint">打 印</el-button>
            </div>
          </div>
          <div id="mytable1" v-loading="loading">
            <div class="table-title" v-if="weekTitle && weekTitle !== ''">{{ weekTitle }}</div>
            <table class="previewTable" border="1" v-if="tableData && tableData.length > 0">
              <tr>
                <th colspan="2">日期</th>
                <th v-for="(item, index) in header">{{ item.weekname }}（{{ item.weekTime }}）</th>
              </tr>
              <tr v-for="(item, index) in tableData">
                <td class="content" rowspan="2" v-if="index === 0">招标内容</td>
                <td class="content" >{{ item.planTime }}</td>
                <td v-for="weekItem in weekList" class="table-content-td">
                  <div class="table-content">
                    <div class="table-content-br"
                      :class="planStyle(sonItem)"
                      v-for="(sonItem, sonIndex) in item[weekItem]"
                      @dblclick="cellDbClick(sonItem)"
                      :key="sonIndex">
                      {{ sonIndex + 1 }}、{{ sonItem.planContent }}-{{ selectDictLabel(dict.type.plan_bidmethods, sonItem.bidmethod) }}-{{ sonItem.deptName }}-{{ selectDictLabel(dict.type.plan_area, sonItem.planArea) }}-（{{ sonItem.planPrice }}万元）
                    </div>
                  </div>
                </td>
              </tr>
            </table>
          </div>
        </div>
      </el-col>
    </el-row>



    <!-- 开标计划弹框 -->
    <el-dialog title="开标记录" :visible.sync="plan.open" width="60%" :close-on-click-modal="false">
      <el-table v-loading="plan.loading" :data="plan.sectionList" border max-height="540px">
        <el-table-column label="序号" type="index"  width="55" align="center"></el-table-column>
        <el-table-column label="招标编号" align="center" prop="sectionId"  width="140" show-overflow-tooltip></el-table-column>
        <el-table-column label="招标名称" align="center" prop="sectionName" show-overflow-tooltip>
          <template slot-scope="scope">
            <span @dblclick="copyText(scope.row.sectionName)">{{ scope.row.sectionName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="招标类别" align="center"  width="80">
          <template slot-scope="scope">
            {{ selectDictLabel(dict.type.sys_bidcategory, scope.row.projectInfo.bidcategory) }}
          </template>
        </el-table-column>
        <el-table-column label="组织方式" align="center"  width="160">
          <template slot-scope="scope">
            {{ selectDictLabel(dict.type.sys_bidmethos, scope.row.bidmethod) }}
          </template>
        </el-table-column>
        <el-table-column label="开标时间" align="center" prop="open" width="140" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.open, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责人"  align="center" prop="projectInfo.assistant"  width="120" show-overflow-tooltip ></el-table-column>
        <el-table-column label="操作" fixed="right"  align="center" class-name="small-padding fixed-width"  width="160">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd(scope.row)"
            >上传</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleExport(scope.row)"
              :disabled="!scope.row.openfilePath"
            >查看</el-button>
            <!-- v-hasPermi="['system:todaySection:export']" -->
             <!-- v-hasPermi="['system:todaySection:upload']" -->
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="plan.total > 0"
        :total="plan.total"
        :page.sync="plan.queryParams.pageNum"
        :limit.sync="plan.queryParams.pageSize"
        @pagination="getList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="plan.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 上传开标记录 -->
    <el-dialog title="上传开标记录" :visible.sync="plan.upload.open" width="40%" append-to-body>
      <el-form ref="form" :model="plan.upload.form" :rules="plan.upload.rules" label-width="80px">
        <el-form-item label="开标记录" prop="openfilePath">
          <file-upload v-model="plan.upload.form.openfilePath"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listSection, todayOpen } from "@/api/projectManage/sectionList"
import { listPlan, getPlan, delPlan, addPlan, updatePlan, getPlanAreaOptions } from "@/api/projectManage/plan";
import printJS from 'print-js'
import { mapGetters } from "vuex";
export default {
  name: "Index",
  dicts: ['plan_time', 'plan_area', 'sys_bidcategory', 'sys_bidmethos', 'plan_bidmethods'],
  data() {
    return {
      // 遮罩层
      loading: true,
      title: '',
      open: false,
      planDateOptions: [],
      planAreaOptions: [],
      planDetail: {},
      tableData: [],
      header: [],
      form: {},
      queryParams: {
        weeks: 0
      },
      weekTitle: '',
      weekList: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],


      // 开标计划
      plan: {
        open: false,
        loading: false,
        queryParams: {
          projectId: '',
          open: '',
          pageNum: 1,
          pageSize: 10,
          deptId: null,
          bidcategorys: null,
        },
        upload: {
          open: false,
          rules: {
            openfilePath: [
              { required: true, message: "开标记录表不能为空", trigger: "change" }
            ],
          },
          form: {
            id: '',
            openfilePath: ''
          }
        },
        sectionList: [],
        total: 0
      }
    }
  },
  computed: {
    ...mapGetters(['roles', 'userInfo'])
  },
  created() {
    if (this.roles) {
      this.form.deptId = this.userInfo.deptId
      this.form.deptName = this.userInfo.dept.deptName
    }
    this.getList()
  },
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 合并列
      if (rowIndex === 0 && columnIndex === 0) {
        return {
          rowspan: 2,
          colspan: 1
        }
      } else if (rowIndex === 1 && columnIndex === 0) {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    },
    rowClass({ row, column,rowIndex,columnIndex}) {
      if(rowIndex===0 && columnIndex===0) {
        this.$nextTick(()=> {
          if(document.getElementsByClassName(column.id).length!==0) {
            document.getElementsByClassName(column.id)[0].setAttribute('rowSpan',2);
            return false
          }
        })
      }
      if(rowIndex===1 && (columnIndex===0 || columnIndex===1)) {
        return {display:'none'}
      }

    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 0) {
        return 'primary-row';
      } else if (rowIndex === 1) {
        return 'success-row';
      }
      return '';
    },
    // 获取会议室
    async getPlanAreaOptions() {
      const queryParams = {
        planDate: this.form.planDate,
        planTime: this.form.planTime,
      }
      const res = await getPlanAreaOptions(queryParams)
      if (res.code == 200) {
        this.planAreaOptions = res.data
      } else {
        this.planAreaOptions = []
      }
      

    },
    // 上一周下一周切换
    handleSwitch(num) {
      if (num === 0) {
        this.queryParams.weeks = num
      } else {
        this.queryParams.weeks += num
      }
      this.getList()
    },
    // 获取招标计划
    getList() {
      this.loading = true
      this.planDateOptions = []
      listPlan(this.queryParams).then(response => {
        response.data.weekHeader.forEach(item => {
          this.planDateOptions.push(item)
        })
        this.weekTitle = response.data.weekTitle
        this.header = response.data.weekHeader
        response.data.content.forEach(item => {
          // console.log('item', item)
          item['content'] = '招标内容'
          // for (const sonkey in item) {
          //   // console.log('sonkey', item[sonkey])
          //   if (item[sonkey] && item[sonkey].length > 0) {
          //     item[sonkey].sort(function (a, b) {
          //       return b.planArea - a.planArea;
          //     })
          //   }
            
          // }
        })
        this.tableData = response.data.content
        this.loading = false
      })
    },
    handlePrint () {
      const printCss = `
        #mytable1 {
          font-family: Arial, sans-serif;
        }
        .table-content {
          text-align: left;
          min-height: 322px;
        }
        .content {
          width: 30px;
          line-height: 1.6;
        }
        td {
          width: 13.6%;
          padding: 4px;
          font-size: 12px;
          line-height: 1.6;
        }
        .table-content-td {
          vertical-align: top;
        }
        th {
          height: 30px;
          font-size: 12px;
        }
        tbody {
          text-align: center;
        }
        table {
          width: 100%;
          border-collapse: collapse;
          text-align: center;
          margin-top: 60px;
          overflow: auto;
        }
        .table-title {
          display: block;
          font-size: 14px;
          font-weight: bold;
          padding: 10px 0 8px 0;
          text-align: center;
          position: absolute;
          top: 20px;
          left: 50%;
          transform: translate(-50%, 0%);
        }
      `
      printJS({
        printable: 'mytable1', // 标签元素id
        type: 'html',
        scanStyles: false,
        style: `@page { size:auto; position: relative; margin-top: 0px; margin-left:16px; margin-right: 24px; }` + printCss,
      });
    },
    async copyText(textToCopy) {
      // navigator clipboard 需要https等安全上下文
      if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        navigator.clipboard.writeText(textToCopy).then(() => {
          this.$modal.msgSuccess('复制成功！')
        })
      } else {
        // 创建text area
        let textArea = document.createElement("textarea");
        textArea.value = textToCopy;
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = "absolute";
        textArea.style.opacity = '0';
        textArea.style.left = "-999999px";
        textArea.style.top = "-999999px";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        let res = new Promise((res, rej) => {
          res(() => {
            document.execCommand('copy')
            textArea.remove();
          })
          rej(false)
        })
        res.then(res => {
          res();
          this.$modal.msgSuccess('复制成功！')
        }).catch(error => {
          this.$modal.msgError('复制失败！')
        })
      }
    },


    // 新增上传开标记录表功能
    cellDbClick(item) {
      console.log('item11111111111111', item)
      
      if (this.roles && (this.roles.indexOf('zb_b') > -1 || this.roles.indexOf('zb_f') > -1)) {
        // 招标部
        if (item.deptId !== this.form.deptId) return
        this.plan.queryParams.deptId = this.userInfo.deptId
        this.plan.queryParams.bidcategorys = null
      } else if (this.roles.indexOf('fg_gf') > -1) {
        // 分管工程服务
        if (item.bidcategory !== 0 && item.bidcategory !== 2) return
        this.plan.queryParams.bidcategorys = [0, 2]
        this.plan.queryParams.deptId = null
      } else if (this.roles.indexOf('fg_h') > -1) {
        // 分管货物
        if (item.bidcategory !== 1) return
        this.plan.queryParams.bidcategorys = [1]
        this.plan.queryParams.deptId = null
      } else if (this.roles.indexOf('gs_l') > -1 || this.roles.indexOf('admin') > -1) {
        this.plan.queryParams.deptId = null
        this.plan.queryParams.bidcategorys = null
      } else {
        this.plan.queryParams.deptId = null
        this.plan.queryParams.bidcategorys = null
        return
      }
      this.plan.open = true
      this.plan.queryParams.projectId = item.projectId
      this.plan.queryParams.open = item.planDate
      this.getSectionList()
    },
    // 开标计划样式判断
    planStyle(item) {
      console.log(item, item.deptId == this.form.deptId)
      
      if (this.roles && (this.roles.indexOf('zb_b') > -1 || this.roles.indexOf('zb_f') > -1)) {
        // 招标部
        if (item.deptId == this.form.deptId) {
          return 'color-high'
        }
      } else if (this.roles.indexOf('fg_gf') > -1) {
        // 分管工程服务
        if (item.bidcategory == 0 || item.bidcategory == 2) {
          return 'color-high'
        }
      } else if (this.roles.indexOf('fg_h') > -1) {
        // 分管货物
        if (item.bidcategory == 1)  {
          return 'color-high'
        }
      } else {
        return ''
      }
      return ''
    },
    // 获取标段列表
    getSectionList() {
      this.plan.loading = true
      listSection(this.plan.queryParams).then(response => {
        this.plan.sectionList = response.rows
        this.plan.total = response.total
        this.plan.loading = false
      });
    },
    reset() {
      this.plan.upload.form = {
        openfilePath: '',
        id: ''
      }
      this.resetForm("form")
    },
    handleAdd(row) {
      this.reset()
      this.plan.upload.open = true
      this.plan.upload.form.id = row.id
    },
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    handleExport(row) {
      const link = document.createElement('a');
      link.href = process.env.VUE_APP_BASE_API + row.openfilePath
      link.download = this.getFileName(row.openfilePath)
      link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
      link.click()
    },
    submitForm() {
      console.log('this.plan.upload.form', this.plan.upload.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          todayOpen(this.plan.upload.form).then(response => {
            this.$modal.msgSuccess("今日开标记录提交成功！")
            this.getSectionList()
            this.cancel()
          })
        }
      })
    },
    cancel() {
      this.plan.upload.open = false
      this.reset()
    }
  }
};
</script>

<style scoped lang="scss">
.home {
  .top-tabs, .bottom-table {
    width: 100%;
  }
  .top-tabs {
    display: flex;
    justify-content: space-between;
    > div {
      width: 50%;
      // border: 1px solid #eeeeee;
      .left-title {
        font-size: 20px;
        font-weight: bold;
        border-bottom: 1px solid #999999;
        line-height: 40px;
      }
    }
    .tab-left {
      padding-right: 10px;
      .left-content {
        padding-top: 12px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .content-tag {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 90px;
          width: 6%;
          background: #eeeeee;
          letter-spacing: 0.2em;
          writing-mode: vertical-lr;
          font-size: 18px;
          font-weight: bold;
          border-radius: 4px;
        }
        .content-list {
          width: 93%;
          display: flex;
          justify-content: space-around;
          height: 90px;
          .list-item {
            border: 1px solid #eeeeee;
            background: #eee;
            border-radius: 4px;
            display: flex;
            align-items: center;
            width: 24%;
            padding: 4px 10px;
            img {
              display: block;
              width: 60px;
              height: 60px;
              // margin-right: 10px;
            }
            .item-content {
              width: 118px;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              > div {
                font-size: 18px;
                padding: 4px 0;
                color: #333333;
                text-align: center;
              }
            }
          }
        }
      }
    }
    .tab-right {
      padding-left: 10px;
      .right-list {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        .list-item {
          width: 405px;
          height: 90px;
          margin-top: 12px;
          background: #eeeeee;
          border-radius: 4px;
          display: flex;
          align-items: center;
          padding: 4px 10px;
          img {
            width: 70px;
            height: 70px;
            display: block;
          }
          .item-left {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size: 18px;
            width: calc((100% - 80px) / 2);
            .item-num {
              margin-top: 4px;
            }
          }
        }
      }
    }
  }
}
.table-header {
  .table-title {
    font-size: 18px;
    font-weight: bold;
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .btn-groups {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
// ::v-deep .el-table {
//   .el-table__body-wrapper {
//     .cell {
//       user-select: none;
//       min-height: 300px;
//     }
//   }
//   .data-time {
//     .cell {
//       display: flex;
//       align-items: center;
//     }
//   }
//   tbody tr:hover > td {
//     background-color: unset !important;
//   }
//   tbody tr > td:hover {
//     background-color: rgba(81, 90, 110, 0.06) !important;
//   }
// }
.table-title {
  display: none;
}
.previewTable {
  margin-top: 12px;
  width: 100%;
  border-color: #999999;
  border-collapse: collapse;
  font-size: 14px;
  color: #333333;
  th, td {
    text-align: left;
    padding: 6px 10px;
    line-height: 1.5;
    font-size: 12px !important;
  }
  td {
    width: 13.6%;
  }
  .table-content-td {
    vertical-align: top;
  }
  th {
    font-size: 14px !important;
    text-align: center;
    height: 40px;
  }
  .content {
    padding: 0 10px;
    width: 30px;
  }
  .table-content {
    min-height: 320px;
    .table-content-br {
      padding: 3px 0;
    }
    .color-high {
      color: red;
      cursor: pointer;
      &:hover {
        color: #1890ff;
      }
    }
  }
}


// 同部门样式变化
::deep .colorHigh {
  color: red;
}
</style>

